const express = require('express');
const bodyParser = require('body-parser');
const QRCode = require('qrcode');
const fs = require("fs");
const cors = require("cors");
// const WechatPay = require("wechat-pay-nodejs");
const app = express();
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/static', express.static('static'));
// 初始化微信支付
// const wechatPayInstance = new WechatPay.WechatPay({
//     appid: 'your_app_id',
//     mchid: 'your_mch_id',
//     cert_private_content: Buffer.from('your_apiclient_key.pem'),
//     cert_public_content: Buffer.from('your_apiclient_cert.pem')
// });

// 创建订单并生成二维码
app.get('/query-product/:productId', async (req, res) => {
    const productId = req.params.productId;
    res.json({
        status: "success",
        data: productsMap[productId]
    });
});
app.get('/place-order/:orderId', async (req, res) => {
    // const { body, out_trade_no, total_fee, spbill_create_ip, notify_url } = req.body;
    // 计算订单号
    // const productId = req.params.productId;
    // const timestamp = Date.now();
    // const randomNum = Math.floor(Math.random() * 1000) + 1;
    let out_trade_no = req.params.orderId;
    const [productId, timestamp, randomNum] = out_trade_no.split("-");
    // 从获取订单金额
    const price = productsMap[productId].Price;
    try {
        // const result = await wechatPayInstance.unifiedOrder({
        //     body,
        //     out_trade_no,
        //     total_fee,
        //     spbill_create_ip,
        //     notify_url,
        //     trade_type: 'NATIVE'
        // });
        const result = {
            code_url: `https://www.baidu.com?orderid=${out_trade_no}`
        }
        const codeUrl = result.code_url;
        const buffer = await QRCode.toBuffer(codeUrl, {
            type: 'png', // 指定图片格式为PNG
            color: {
                dark: '#000000', // 指定二维码颜色
                light: '#ffffff' // 指定背景颜色
            },
            width: 200, // 指定二维码宽度
            height: 200 // 指定二维码高度
        });
        // 设置响应头，指定返回的是图片
        res.type('png');

        // 将二维码图片作为响应返回
        res.send(buffer);
        // 生成二维码并返回给前端
        // const qrCodeUrl = await QRCode.toDataURL(codeUrl);
        // res.json({ qrCodeUrl });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: err.message });
    }
});
app.get('/check-order/:orderId', async (req, res) => {
    const orderId = req.params.orderId;
    res.json({
        status: "success",
        data: {
            orderId: orderId,
            price: "19.99",
            secrets: "ayuekekvkdie"
        }
    });
});
// 初始化数据库
const products = JSON.parse(fs.readFileSync(`./assets/products.json`, 'utf-8')).ProductList;
const productsMap = {};
products.forEach(p => {
    productsMap[p.ProductId] = p;
});

// app.all('*',function (req, res, next) {
//     res.setHeader("Access-Control-Allow-Origin", "*");
//     res.setHeader("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
//     res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials");
//     // res.setHeader("Content-Type", "application/json;charset=utf-8");
//     next();
// });

app.listen(3999, () => {
    console.log('Server is running on port 3999');
});
